// pages/home/home.js
const HomeHttp = require("../../../utils/HomeHttp");
const KindHttp = require('../../../utils/KindHttp');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 主页轮播图
        homebanners: [],
        //猜你喜欢
        guesslikes: [],
        // 定位城市
        currentCity: "",
        scrollTop: 0,
        shopNum: 0
    },
    // 跳转到分类
    handleKind(e) {
        var { aid } = e.currentTarget.dataset;
        wx.setStorageSync('homeToKindById', aid)
        wx.switchTab({
            url: `/pages/KindIndex/kind/kind`,
        })
    },
    // 跳转到城市
    handleCity() {
        wx.navigateTo({
            url: '/pages/HomeIndex/city/city',
        })
    },
    // 此处方法跳转到消息中心
    handleMessage() {
        wx.navigateTo({
            url: '/pages/HomeIndex/messageCenter/messageCenter',
        })
    },
    // 此方法跳转到购物车
    handleShopping() {
        wx.switchTab({
            url: '/pages/ShopIndex/shopping/shopping',
        })
    },
    // 跳转到搜索页面
    handleSearch() {
        wx.navigateTo({
            url: '/pages/Search/Search',
        })
    },
    // 城市切换
    getCity() {
        //1.获取经纬度
        wx.getLocation({
            altitude: false,
            type: 'wgs84',
            success: (res) => {
                var key = `2KEBZ-FM4K3-UVE3W-YN4SD-3OT7K-LHFTI`;
                var { latitude, longitude } = res;
                var url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&get_poi=1`;
                wx.request({
                    url,
                    success: (res) => {
                        var currentCity = res.data.result.address_component.city;
                        var storageCity = wx.getStorageSync('city');
                        //3.当缓存中的城市和当前地理位置不一致的时候弹窗
                        if (currentCity != storageCity) {
                            wx.showModal({
                                title: '切换城市',
                                content: '当前城市不是您所在城市',
                                showCancel: true,
                                cancelText: '取消',
                                cancelColor: '#000000',
                                confirmText: '确定',
                                confirmColor: '#3CC51F',
                                success: (result) => {
                                    //点击确定就设置为当前地理位置
                                    if (result.confirm) {
                                        this.setData({
                                            currentCity
                                        })
                                        wx.setStorageSync("city", currentCity);
                                    } else {
                                        //取消就设置为缓存中的城市
                                        this.setData({
                                            currentCity: storageCity || '尚未定位'
                                        })
                                    }
                                },
                            });
                        }
                    },
                })
            },
        })
    },
    // 加入购物车
    async onClick(e) {
        var { aid, collect } = e.currentTarget.dataset
        if (collect === false) {
            wx.request({
                url: 'http://122.112.142.6:8888/api/kindCollect',
                data: {
                    id: aid,
                    collect: true
                },
                header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                method: 'POST',
                success: async (res) => {
                    if (res.data.msg == "收藏成功" && res.data.status == 200) {
                        wx.showToast({
                            title: '加入购物车成功 !',
                            icon: 'none',
                        })
                    } else {
                        wx.showToast({
                            title: '已经在购物车中了',
                            icon: 'none',
                        })
                    }
                    var userCollRes = await KindHttp.getUserCollect();
                    // console.log(userCollRes.data.res);
                    this.setData({
                        shopNum: userCollRes.data.res.length
                    })
                    wx.setTabBarBadge({
                        index: 2,
                        text: String(this.data.shopNum),
                    })
                },
            })

        } else {
            // wx.request({
            //     url: 'http://122.112.142.6:8888/api/kindCollect',
            //     data: {
            //         id: aid,
            //         collect: false
            //     },
            //     header: {
            //         "Content-Type": "application/x-www-form-urlencoded"
            //     },
            //     method: 'POST',
            //     success: (res) => {
            //         if (res.data.msg == "取消收藏") {
            //             let removeToPull = true;
            //             this.triggerEvent('removeToPull', removeToPull)
            //             wx.showToast({
            //                 title: '取消加入成功 !',
            //                 icon: 'none',
            //             })
            //         }
            //     },
            // })
            wx.showToast({
                title: '已经在购物车中了',
                icon: 'none',
            })

        }
    },
    // 商品详情页
    handleProductDetail(e) {
        var { aid } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/ProductDetail/ProductDetail?id=${aid}`,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        // 调用切换城市方法
        this.getCity();
        //获取主页轮播
        var homebannerRes = await HomeHttp.getHomeBanner();
        //获取主页猜你喜欢
        var guesslikeRes = await HomeHttp.getHomeGuesslike();
        var userCollRes = await KindHttp.getUserCollect();
        this.setData({
            homebanners: homebannerRes.data.res,
            guesslikes: guesslikeRes.data.res,
            shopNum: userCollRes.data.res.length
        })
        wx.setTabBarBadge({
            index: 2,
            text: String(userCollRes.data.res.length),
        })
    },
    /**
     * 监听滚动条
     */
    onPageScroll: function (e) {
        this.setData({
            scrollTop: e.scrollTop
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: async function () {
        //获取缓存中城市的值
        var city = wx.getStorageSync('city');
        this.setData({
            currentCity: city
        });
        var userCollRes = await KindHttp.getUserCollect();
        this.setData({
            shopNum: userCollRes.data.res.length
        })
        wx.setTabBarBadge({
            index: 2,
            text: String(this.data.shopNum),
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})